package lovemusic.lanou.com.newsmusic.ui.activity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;

import lovemusic.lanou.com.newsmusic.R;
import lovemusic.lanou.com.newsmusic.service.PlayMusicService;
import lovemusic.lanou.com.newsmusic.utils.SystemUtils;
import lovemusic.lanou.com.newsmusic.utils.UIUtils;

/**
 * 应用的引导页面启动播放音乐的服务
 * Created by lanouhn on 2016/9/29.
 */
public class SplashActivity extends AppCompatActivity{

    private ServiceConnection mPlayServiceConnection;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        checkService();
    }

    private void checkService() {
        if (SystemUtils.isServiceRunning(this, PlayMusicService.class)){
            startAppActivity();
            finish();
        }else{
            startService();
            UIUtils.getHandle().postDelayed(new Runnable() {
                @Override
                public void run() {
                    bindService();
                }
            },1000);
        }
    }

    /**
     * 实现跳转
     */
    private void startAppActivity() {
        Intent intent=new Intent(this,MainActivity.class);
        startActivity(intent);
    }

    /**
     * 启动服务
     */
    private void startService() {
        Intent intent=new Intent(this,PlayMusicService.class);
        startService(intent);
    }

    private void bindService() {
        mPlayServiceConnection=new PlayServiceConnection();
        Intent intent=new Intent(this,PlayMusicService.class);
        bindService(intent,mPlayServiceConnection, Context.BIND_AUTO_CREATE);
    }

    private class PlayServiceConnection implements ServiceConnection{

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            PlayMusicService playService = ((PlayMusicService.PlayBinder)iBinder).getService();
            startAppActivity();
            finish();
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {

        }
    }

    @Override
    protected void onDestroy() {
        if (mPlayServiceConnection != null) {
            unbindService(mPlayServiceConnection);
        }
        super.onDestroy();
    }


}
